package com.infosystem.demo.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OssConfig {
    //Domain
    public static String domain;

    //Endpoint
    public static String endpoint;

    //Bucket Name of OSS Example.
    public static String bucketName;

    //access id and key
    public static String accessKeyId;
    public static String accessKeySecret;

    @Value("${alibaba.cloud.oss.domain}")
    public void setDomain(String domain) {
        OssConfig.domain = domain;
    }

    @Value("${alibaba.cloud.oss.endpoint}")
    public void setEndpoint(String endpoint) {
        OssConfig.endpoint = endpoint;
    }

    @Value("${alibaba.cloud.oss.bucket}")
    public void setBucketName(String bucketName) {
        OssConfig.bucketName = bucketName;
    }

    @Value("${alibaba.cloud.accessKeyId}")
    public void setAccessKeyId(String accessKeyId) {
        OssConfig.accessKeyId = accessKeyId;
    }
    @Value("${alibaba.cloud.accessKeySecret}")
    public void setAccessKeySecret(String accessKeySecret) {
        OssConfig.accessKeySecret = accessKeySecret;
    }

    @Bean
    public ApplicationRunner ossBucketInitRunner(OSS ossClient) {
        return args -> {
            if (!ossClient.doesBucketExist(bucketName)) {
                ossClient.createBucket(bucketName);
            }
        };
    }

    @Bean
    public OSS OSSClient() {
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }
}
